import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入组件
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'
import Rights from '../components/power/Rights.vue'
import Roles from '../components/power/Roles.vue'
import Categories from '../components/goods/Categories.vue'
import Params from '../components/goods/Params.vue'
import GoodsList from '../components/goods/List.vue'
import Add from '../components/goods/Add.vue'
import Order from '../components/order/Order.vue'
import Report from '../components/report/Report.vue'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      // 页
      path: '/',
      redirect: '/login'
    },
    {
      // 登录页
      path: '/login',
      component: Login
    },
    {
      // 主页 装换成欢迎界面了
      path: '/home',
      component: Home,
      redirect: '/welcome',
      children: [
        // 欢迎界面
        { path: '/welcome', component: Welcome },
        // 用户管理
        { path: '/users', component: Users },
        // 权限管理-权限列表
        { path: '/rights', component: Rights },
        // 权限管理-角色列表
        { path: '/roles', component: Roles },
        // 商品管理-商品分类
        { path: '/categories', component: Categories },
        // 商品管理-分类参数
        { path: '/params', component: Params },
        // 商品管理-商品列表
        { path: '/goods', component: GoodsList },
        // 商品管理-添加商品列表
        { path: '/goods/add', component: Add },
        // 订单管理-订单列表
        { path: '/orders', component: Order },
        // 数据统计-数据统计
        { path: '/reports', component: Report },
      ]
    }
  ]
})

// 挂载路由导航守卫
// 为路由对象，添加beforeEach导航守卫
router.beforeEach((to, from, next) => {
  // to将要访问的路径
  // from 代表从哪个路径跳转而来
  // next是一个函数，表示放行
  // next()放行    next("/login')强制跳转

  // 如果用户访问的登录页，直接放行
  if (to.path === '/login') return next()
  // 获取token
  const tokenstr = window.sessionStorage.getItem('token')
  // 没有token，强制跳转到登录页
  if (!tokenstr) return next('/login')
  next()
})

export default router
